layui.define(['carousel', 'jquery', 'element', 'flow', 'laytpl', 'element', 'laypage', 'form', 'util'], function (exports) {
    var carousel = layui.carousel, $ = layui.$, flow = layui.flow, laytpl = layui.laytpl, element = layui.element, laypage = layui.laypage, form = layui.form, util = layui.util;
    var commons = {
        Init: function () {

        },
        clickBind: function () {
            let area_input = document.getElementById('content'); let area_output = document.getElementById('outtxt');
            $(".cle").bind("click", function () { area_input.value = ''; area_output.value = ''; });
            $(".copy").bind("click", function () {
                var txt = area_output.value; if (txt === undefined || txt === '' || txt === null) { layer.msg("没有输出内容.", { icon: 2 }); return; }
                if (XEClipboard.copy(txt)) { layer.msg("复制成功.", { icon: 1 }); }
                else { layer.msg("复制失败.", { icon: 2 }); }
            });
        },
        toUint8Arr: function (str) {
            const buffer = [];
            for (let i of str) {
                const _code = i.charCodeAt(0);
                if (_code < 0x80) {
                    buffer.push(_code);
                } else if (_code < 0x800) {
                    buffer.push(0xc0 + (_code >> 6));
                    buffer.push(0x80 + (_code & 0x3f));
                } else if (_code < 0x10000) {
                    buffer.push(0xe0 + (_code >> 12));
                    buffer.push(0x80 + (_code >> 6 & 0x3f));
                    buffer.push(0x80 + (_code & 0x3f));
                }
            }
            return Uint8Array.from(buffer);
        },
        Uint8ArrayToString: function (fileData) {
            var dataString = "";
            for (var i = 0; i < fileData.length; i++) {
                dataString += String.fromCharCode(fileData[i]);
            }
            return dataString
        },
    }
    commons.clickBind();
    commons.Init()
    exports('common', commons)
    var excel2json = {
        ctyperow: function (obj, fgefu, ctype) {/*excel转json数据 输入对象,分隔符对象，转换值（0转成对象,1转成数组）*/
            var fgf = /\t/;
            var code = obj.value;
            fgf = fgefu.value || fgf;
            var datas = code.split("\n");
            var html = "[\n";
            var keys = [];
            for (var i = 0; i < datas.length; i++) {
                var ds = datas[i].split(fgf);
                if (i == 0) {
                    if (ctype == "0") { keys = ds; } else { html += "["; for (var j = 0; j < ds.length; j++) { html += '"' + ds[j] + '"'; if (j < ds.length - 1) { html += ","; } } html += "],\n"; }
                }
                else {
                    if (ds.length == 0) continue; if (ds.length == 1) { ds[0] == ""; continue; }
                    html += ctype == "0" ? "{" : "[";
                    for (var j = 0; j < ds.length; j++) {
                        var d = ds[j];
                        if (d == "") continue;
                        if (ctype == "0") { html += '"' + keys[j] + '":"' + d + '"'; } else { html += '"' + d + '"'; }
                        if (j < ds.length - 1) { html += ','; }
                    }
                    html += ctype == "0" ? "}" : "]"; if (i < datas.length - 1) html += ",\n";
                }
            }
            html += "\n]";
            return html;
        }
    }; exports('excel2json', excel2json)
    var JsCodem = {
        compile: function (obj) {
            var txtcode = obj.value;
            var c = String.fromCharCode(txtcode.charCodeAt(0) + txtcode.length);
            for (var i = 1; i < txtcode.length; i++) {
                var x = String.fromCharCode(txtcode.charCodeAt(i) + txtcode.charCodeAt(i - 1));
                c += x;
            }
            return escape(c);
        }
        , uncompile: function (obj) {
            var code = obj.value;
            code = unescape(code);
            var c = String.fromCharCode(code.charCodeAt(0) - code.length);
            for (var i = 1; i < code.length; i++) {
                var x = String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
                c += x;
            }
            return c;
        }
    }; exports('JsCodem', JsCodem)
    var Get2Json = {
        Jsonget: function (obj, type) { /*   1JSON转GET 2 */
            var content = obj.value;
            if (type == 1) {
                content = content.replace(/\t/g, "");
                content = content.replace(/\"/g, "").replace("{", "").replace("}", "").replace(",", "&").replace(":", "=");
                content = content.replace(/\"/g, "").replace(/{/g, "").replace(/}/g, "").replace(/,/g, "&").replace(/:/g, "=");
            }
            else {
                content = content.replace(/&/g, '","').replace(/=/g, '":"');
                content = '{"' + content + '"}';
            }
            return content;
        }
    }; exports('Get2Json', Get2Json)
    var HashCode = {
        calHash: function (obj, algot, keyt) {/* hash加密(输入内容 加密类型 密钥) */
            let text = obj.value;
            if (!text) { return; }
            let key = keyt.value;
            let algo = algot.value;
            let hash;
            switch (algo) {
                case 'MD5': hash = CryptoJS.MD5(text); break;
                case 'SHA1': hash = CryptoJS.SHA1(text); break;
                case 'SHA224': hash = CryptoJS.SHA224(text); break;
                case 'SHA256': hash = CryptoJS.SHA256(text); break;
                case 'SHA384': hash = CryptoJS.SHA384(text); break;
                case 'SHA512': hash = CryptoJS.SHA512(text); break;
                case 'Hmac-MD5': hash = CryptoJS.HmacMD5(text, key); break;
                case 'Hmac-SHA1': hash = CryptoJS.HmacSHA1(text, key); break;
                case 'Hmac-SHA224': hash = CryptoJS.HmacSHA224(text, key); break;
                case 'Hmac-SHA256': hash = CryptoJS.HmacSHA256(text, key); break;
                case 'Hmac-SHA384': hash = CryptoJS.HmacSHA384(text, key); break;
                case 'Hmac-SHA512': hash = CryptoJS.HmacSHA512(text, key); break;
            }
            return hash;
        }
    }; exports('HashCode', HashCode)
    var ImgToBase64 = {
        matSize: function (size, len, units) {
            let unit;
            units = units || ['B', 'K', 'M', 'G', 'TB'];
            while ((unit = units.shift()) && size > 1024) { size = size / 1024; }
            return (unit === 'B' ? size : size.toFixed(len === undefined ? 2 : len)) + unit;
        }
        , base64oImage: function (img_input, area_base64) {
            let base64 = area_base64.value;
            if (!base64.startsWith('data:image')) {
                base64 = 'data:image/jpeg;base64,' + base64
            }
            img_input.innerHTML = `<img src="${base64}" style="width:100%;">`;
        }
        , loadImage: function (img_input, file_name, area_base64, file) {
            let reader = new FileReader();
            reader.onload = function (e) {
                var size = ImgToBase64.matSize(file.size, null, null);
                file_name.innerHTML = file.name + `&nbsp;&nbsp;<a>[${size}]</a>`;
                img_input.innerHTML = `<img src="${e.target.result}" style="width:100%;">`;
                area_base64.value = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    }; exports('ImgToBase64', ImgToBase64)
    var GB2312UnicodeConverter = {
        ToUnicode: function (str) {
            var txt = escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u');
            return txt.replace(/%7b/gi, '{').replace(/%7d/gi, '}').replace(/%3a/gi, ':').replace(/%2c/gi, ',').replace(/%27/gi, '\'').replace(/%22/gi, '"').replace(/%5b/gi, '[').replace(/%5d/gi, ']').replace(/%3D/gi, '=').replace(/%20/gi, ' ').replace(/%3E/gi, '>').replace(/%3C/gi, '<').replace(/%3F/gi, '?');//
        },
        ToGB2312: function (str) {
            return unescape(str.replace(/\\u/gi, '%u'));
        }
    }; exports('GB2312UnicodeConverter', GB2312UnicodeConverter)
    var JsonTrans = {
        yasuo: function (obj, ii) { /** 1 压缩 2 转义 3 压缩转义 4 去除转义*/
            var text = obj.value;
            if (ii == 1 || ii == 3) {
                text = text.split("\n").join(" ");
                var t = [];
                var inString = false;
                for (var i = 0, len = text.length; i < len; i++) {
                    var c = text.charAt(i);
                    if (inString && c === inString) {
                        if (text.charAt(i - 1) !== '\\') {
                            inString = false;
                        }
                    } else if (!inString && (c === '"' || c === "'")) {
                        inString = c;
                    } else if (!inString && (c === ' ' || c === "\t")) {
                        c = '';
                    }
                    t.push(c);
                }
                text = t.join('');
            }
            if (ii == 2 || ii == 3) {
                text = text.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"");
            }
            if (ii == 4) {
                text = text.replace(/\\\\/g, "\\").replace(/\\\"/g, '\"');
            }
            return text;
        }
        , trim: function (str) {
            return str.replace(/(^\s*)|(\s*$)/g, '');
        }
        , u2h: function (obj) {
            var text = obj.value;
            text = JsonTrans.trim(text);
            return GB2312UnicodeConverter.ToGB2312(text);
        }
        , h2u: function (obj) {
            var text = obj.value;
            text = JsonTrans.trim(text);
            return GB2312UnicodeConverter.ToUnicode(text);
        }
        , cnChar2EnChar: function (obj) {
            var str = obj.value;
            str = str.replace(/\’|\‘/g, "'").replace(/\“|\”/g, "\"");
            str = str.replace(/\【/g, "[").replace(/\】/g, "]").replace(/\｛/g, "{").replace(/\｝/g, "}");
            str = str.replace(/，/g, ",").replace(/：/g, ":");
            return str;
        }
    }; exports('JsonTrans', JsonTrans)
    var JsonColor = {
        tab: "  "
        , IsArray: function (obj) {
            return obj &&
                typeof obj === 'object' &&
                typeof obj.length === 'number' &&
                !(obj.propertyIsEnumerable('length'));
        }

        , Process: function (content, checked, canvas) {
            var json = content.value;
            if (checked) {
                json = unescape(json.replace(/\\u/gi, '%u'));
            }
            canvas.style.display = "block";
            var html = "";
            try {
                if (json == "") json = "\"\"";
                var obj = eval("[" + json + "]");
                html = this.ProcessObject(obj[0], 0, false, false, false);
                canvas.innerHTML = "<PRE class='CodeContainer'>" + html + "</PRE>";
            } catch (e) {
                canvas.innerHTML = "JSON语法错误,不能格式化,错误信息:\n" + e.message;
            }
        }
        , ProcessObject: function (obj, indent, addComma, isArray, isPropertyContent) {
            var html = "";
            var comma = (addComma) ? "<span class='Comma'>,</span> " : "";
            var type = typeof obj;
            if (this.IsArray(obj)) {
                if (obj.length == 0) {
                    html += this.GetRow(indent, "<span class='ArrayBrace'>[ ]</span>" + comma, isPropertyContent);
                } else {
                    html += this.GetRow(indent, "<span class='ArrayBrace'>[</span>", isPropertyContent);
                    for (var i = 0; i < obj.length; i++) {
                        html += this.ProcessObject(obj[i], indent + 1, i < (obj.length - 1), true, false);
                    }
                    html += this.GetRow(indent, "<span class='ArrayBrace'>]</span>" + comma);
                }
            } else if (type == 'object' && obj == null) {
                html += this.FormatLiteral("null", "", comma, indent, isArray, "Null");
            } else if (type == 'object') {
                var numProps = 0;
                for (var prop in obj) numProps++;
                if (numProps == 0) {
                    html += this.GetRow(indent, "<span class='ObjectBrace'>{ }</span>" + comma, isPropertyContent);
                } else {
                    html += this.GetRow(indent, "<span class='ObjectBrace'>{</span>", isPropertyContent);
                    var j = 0;
                    for (var prop in obj) {
                        html += this.GetRow(indent + 1, '<span class="PropertyName">"' + prop + '"</span>: ' + this.ProcessObject(obj[prop], indent + 1, ++j < numProps, false, true));
                    }
                    html += this.GetRow(indent, "<span class='ObjectBrace'>}</span>" + comma);
                }
            } else if (type == 'number') {
                html += this.FormatLiteral(obj, "", comma, indent, isArray, "Number");
            } else if (type == 'boolean') {
                html += this.FormatLiteral(obj, "", comma, indent, isArray, "Boolean");
            } else if (type == 'function') {
                obj = FormatFunction(indent, obj);
                html += this.FormatLiteral(obj, "", comma, indent, isArray, "Function");
            } else if (type == 'undefined') {
                html += this.FormatLiteral("undefined", "", comma, indent, isArray, "Null");
            } else {
                html += this.FormatLiteral(obj, "\"", comma, indent, isArray, "String");
            }
            return html;
        }
        , FormatLiteral: function (literal, quote, comma, indent, isArray, style) {
            if (typeof literal == 'string')
                literal = literal.split("<").join("&lt;").split(">").join("&gt;");
            var str = "<span class='" + style + "'>" + quote + literal + quote + comma + "</span>";
            if (isArray) str = this.GetRow(indent, str);
            return str;
        }
        , FormatFunction: function (indent, obj) {
            var tabs = "";
            for (var i = 0; i < indent; i++) tabs += this.tab;
            var funcStrArray = obj.toString().split("\n");
            var str = "";
            for (var i = 0; i < funcStrArray.length; i++) {
                str += ((i == 0) ? "" : tabs) + funcStrArray[i] + "\n";

            }
            return str;
        }
        , GetRow: function (indent, data, isPropertyContent) {
            var tabs = "";
            for (var i = 0; i < indent && !isPropertyContent; i++) tabs += this.tab;
            if (data != null && data.length > 0 && data.charAt(data.length - 1) != "\n")
                data = data + "\n";
            return tabs + data;
        }
    }; exports('JsonColor', JsonColor)
    var Morse = {
        standard: { 'A': '01', 'B': '1000', 'C': '1010', 'D': '100', 'E': '0', 'F': '0010', 'G': '110', 'H': '0000', 'I': '00', 'J': '0111', 'K': '101', 'L': '0100', 'M': '11', 'N': '10', 'O': '111', 'P': '0110', 'Q': '1101', 'R': '010', 'S': '000', 'T': '1', 'U': '001', 'V': '0001', 'W': '011', 'X': '1001', 'Y': '1011', 'Z': '1100', '0': '11111', '1': '01111', '2': '00111', '3': '00011', '4': '00001', '5': '00000', '6': '10000', '7': '11000', '8': '11100', '9': '11110', '.': '010101', ',': '110011', '?': '001100', '\'': '011110', '!': '101011', '/': '10010', '(': '10110', ')': '101101', '&': '01000', ':': '111000', ';': '101010', '=': '10001', '+': '01010', '-': '100001', '_': '001101', '"': '010010', '$': '0001001', '@@': '011010', }
        , option: ['/', '.', '-']
        , standardReverse: {}
        , unicodeHexMorse: function (ch) {
            let r = [];
            for (let i = 0; i < ch.length; i++)
                r[i] = ('00' + ch.charCodeAt(i).toString(16)).slice(-4);
            r = r.join('');
            r = parseInt(r, 16).toString(2);
            return r;
        }

        , encode: function (obj) {
            var msg = obj.value;
            let morse = []; msg = msg.replace(/\s+/g, '').toLocaleUpperCase().split('');
            let ch, r;
            for (let i = 0, l = msg.length; i < l; i++) {
                ch = msg[i]; r = this.standard[ch];
                if (!r) r = this.unicodeHexMorse(ch);
                morse.push(r.replace(/0/g, this.option[1]).replace(/1/g, this.option[2]));
            }
            return morse.join(this.option[0]);
        }
        , morseHexUnicode: function (mor) {
            mor = parseInt(mor, 2);
            if (isNaN(mor)) return '';
            return unescape('%u' + mor.toString(16));
        }
        , decode: function (obj) {
            var morse = obj.value;
            let msg = [];
            morse = morse.split(this.option[0]);
            for (let key in this.standard) {
                this.standardReverse[this.standard[key]] = key;
            }
            let mor, r;
            for (let i = 0, l = morse.length; i < l; i++) {
                mor = morse[i].replace(/\s+/g, '').replace(new RegExp('\\' + this.option[1], 'g'), '0').replace(new RegExp('\\' + this.option[2], 'g'), '1');
                r = this.standardReverse[mor];
                if (!r) r = this.morseHexUnicode(mor);
                msg.push(r);
            }
            return msg.join('');
        }
    }; exports('Morse', Morse)

});